from datetime import datetime, timedelta
from typing import Optional, Dict, List, Tuple
import pandas as pd
from loguru import logger
from services.data_view_plugin_service import DataViewPluginService
from calc_utils import calculate_percentile_rank_series


class MarginTradingModel:
    
    def __init__(self):
        self.data_service = DataViewPluginService()

    def get_default_date_range(self) -> Tuple[str, str]:
        end_date = datetime.now()
        start_date = end_date - timedelta(days=3*365)
        return start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d')

    def get_margin_trading_data(self, start_date: str, end_date: str) -> Optional[pd.DataFrame]:
        """获取融资融券数据"""
        return self.data_service.get_margin_trading_data(start_date, end_date)

    def get_total_market_volume(self, start_date: str, end_date: str) -> Optional[pd.DataFrame]:
        """获取全市场成交额数据"""
        return self.data_service.get_total_market_volume(start_date, end_date)

    def calculate_financing_ratio(self, df: pd.DataFrame, market_volume_df: pd.DataFrame) -> Optional[pd.DataFrame]:
        """计算融资买入比例"""
        return self.data_service.calculate_financing_ratio(df, market_volume_df)

    def calculate_percentile_rank(self, data: List[float], window: int = 250) -> List[float]:
        """计算百分位数排名"""
        percentile_data = calculate_percentile_rank_series(data, window=window)
        return percentile_data.tolist()

    def process_exchange_data(self, df: pd.DataFrame, exchange: str, field: str) -> Dict:
        """处理交易所数据"""
        return self.data_service.process_exchange_data(df, exchange, field)

    @staticmethod
    def get_exchange_configs():
        """获取交易所配置"""
        return {
            'exchanges': ['SSE', 'SZSE', 'all'],
            'colors': ['#ff6b6b', '#4ecdc4', '#007bff'],
            'names': ['上海证券交易所', '深圳证券交易所', '全市场']
        }